<?php
require_once('sub.inc.php');


if( $_SERVER['QUERY_STRING'] !== "" ){
	$code = clean($_SERVER['QUERY_STRING']);
	if(preg_match("/(.*)\-/", $code, $ray)){
		$code = $ray[1];
		$preview = true;
	}
	$res = mysqli_query($GLOBALS['con'], "SELECT `url`,`id` FROM `links` WHERE `code` LIKE BINARY '$code'");
	if( $row = mysqli_fetch_array($res) ){
		if($preview){
			print "<html>The URL you are requesting is ";
			if(preg_match("/http:\/\/(.*)\.(.*).org\/wiki\/(.*)/", $row['url'], $ray)){
				print "for the <u>" . langLookup($ray[1]) . "</u> edition of <u>" . ucfirst($ray[2]) . "</u>.  The article is titled [[<a href=\"{$row['url']}\">".cleanUp($ray[3])."</a>]]";
			}else{
				print ": <a href=\"{$row['url']}\">{$row['url']}</a>";
			}

		}else{
			header('Location: '. $row['url'], 307);
		}
		
		$res2 = mysqli_query($GLOBALS['con'], "SELECT `id` from `domains` WHERE `tld`='{$_SERVER['SERVER_NAME']}'");
		if( $row2 = mysqli_fetch_array($res2) ){
			$domain = $row2['id'];
		}else{
			$domain = '0';
		}

		mysqli_query($GLOBALS['con'], "INSERT INTO `logs` (`event`, `relatedid`, `message`, `message2`, `ip`, `domain`) VALUES ('HIT', '{$row['id']}', '{$_SERVER['HTTP_USER_AGENT']}', '{$_SERVER['HTTP_REFERER']}', '{$_SERVER['REMOTE_ADDR']}', '$domain')");
	}else{
		print "Sorry, that's not a valid code.";
	}
}else{
	print "<h1>enwn.net v0.2</h1><br>URL Shortening by the <a href=\"http://en.wikinews.org\">English Wikinews</a> community."; 
}


function langLookup($code){
	$lang = array(
		'en'=>'English',
		'sr'=>'Siberian',
		'ja'=>'Japanese',
		'de'=>'German',
		'zh'=>'Chinese'
	);

	if(!is_null($lang[$code])){
		return($lang[$code]);
	}else{
		return(strtoupper($code));
	}
}

function cleanUp($title){
	$in = array(
		"/_/",
	);
	$out = array(
		" ",
	);
	$title = preg_replace($in, $out, $title);
	$title = urldecode($title);
	return $title;
}

?>
